from jmcomic import JmOptionPlugin
from jmcomic.jm_option import *
from utils.PDFMergerTool import PDFMergerTool
import time
from pathlib import Path

class MyPDFMergerPlugin(JmOptionPlugin):
    # 指定你的插件的key
    plugin_key = 'mypdfmerger'

    # 实现invoke方法
    def invoke(self,
               photo: JmPhotoDetail = None,
               album: JmAlbumDetail = None,
               downloader=None,
               pdf_dir_name:str="pdf",#不带斜杠
               filename_rule='Pindex',
               delete_original_file=False,#是否删除源文件
               **kwargs,
               ):
        if album is None:
            jm_log('wrong_usage', 'mypdfmerger必须运行在after_album时')
            return  # 添加 return 语句
        self.log(f"注意！！！！！！源pdf名称需要数字顺序命名！！！！！！")
        pdf_dir = str(Path(self.option.dir_rule.decide_album_root_dir(album) + pdf_dir_name))
        self.log(f"源pdf存放路径：{pdf_dir}")
        # 重试机制
        max_retries = 5
        for attempt in range(max_retries):
            try:
                PDFMergerTool.split_and_merge_pdfs(pdf_dir, album.name, delete_original_file)
                break  # 如果成功，退出循环
            except Exception as e:
                self.log(f"合并 PDF 时发生错误：{e}")
                if attempt < max_retries - 1:
                    self.log(f"等待 10 秒后重试...（第 {attempt + 1} 次）")
                    time.sleep(10)
                else:
                    self.log("重试 5 次后仍然失败，终止操作。")
        
# 让plugin类生效
JmModuleConfig.register_plugin(MyPDFMergerPlugin)